#encoding:utf8

import io
import os
import re
import socket

hosts_path	= r'C:\WINDOWS\system32\drivers\etc\hosts'

def update_google():
	'''update ip address of google'''
	ip	= socket.gethostbyname('www.google.cn')
	print('The current google ip is %s'%ip)
	
	pattern		= re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
	config_name	= os.path.join(os.path.dirname(__file__), 'google.txt')
	address_list= [item for item in io.open(config_name).read().split() if not pattern.match(item.strip())]

	splitter	= '#---google---'
	hostList	= '%s\n'%(splitter)
	for address in address_list:
		hostList+= '%s\t%s\n'%(ip, address)

	with io.open(hosts_path, 'r+', encoding= 'gbk') as f:
		text	= f.read()
		text	= text.split(splitter)[0] + hostList

		f.seek(0)
		f.write(text)

#######################################################################################
def main():
	update_google()

if __name__=='__main__':main()
